<script setup>
import { ref } from 'vue'

import {
  ScenicAreaUpdateService,
  ScenicAreaAddService,
  ScenicAreaAddImgService,
  delImagesService
} from '@/api/scenicArea'

import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

const formRef = ref(null)
const visibleDrawer = ref(false)
const maprefLo = ref()
const maprefLa = ref()

const defaultModel = ref({
  id: null,
  scenicAreaInfo: '',
  scenicAreaLatitude: '',
  scenicAreaLongitude: '',
  scenicAreaName: '',
  scenicAreaVoice: null,
  scenicAreaImages: [],
  scenicAreaImage: []
})
const dialogVisible = ref(false)
const formModel = ref({
  ...defaultModel.value
})
const imgUrl = ref('')
const upload = ref()
const fileList = ref([])
const videoList = ref([])
const videoUrl = ref('')
const editorRef = ref()
// 图片
const onSelectFile = (uploadFile) => {
  if (!uploadFile) return
  if (!(uploadFile.raw instanceof File)) {
    console.error('uploadFile.raw is not a File object:', uploadFile.raw)
    return
  }

  if (uploadFile) {
    if (!Array.isArray(formModel.value.scenicAreaImages)) {
      formModel.value.scenicAreaImages = []
    }
    const file = uploadFile.raw
    formModel.value.scenicAreaImages.push(file)
    console.log(
      'formModel.value.scenicAreaImages',
      formModel.value.scenicAreaImages
    )
    fileList.value = formModel.value.scenicAreaImages.map((image) => ({
      url: URL.createObjectURL(image),
      name: image.name,
      raw: image
    }))

    console.log('File selected:', fileList) // 打印文件信息
  }
}

// 图片删除
const handleRemove = async (file) => {
  if (!Array.isArray(fileList.value)) {
    ElMessage.error('文件列表数据格式错误，请刷新页面后重试')
    return
  }

  const index = fileList.value.findIndex((item) => item.raw === file.raw)
  if (index === -1) {
    ElMessage.error('文件未找到')
    return
  }

  // 获取当前文件列表和图片列表
  // 对应参数
  console.log(index, formModel.value.id)
  const params = new URLSearchParams()
  params.append('id', formModel.value.id)
  params.append('index', index)
  console.log('params', params)

  try {
    const res = await delImagesService(params)
    console.log('res', res)
    if (res && res.data.code === 200) {
      ElMessage.success('删除成功')

      // 从 formModel.value.scenicAreaImages 中移除已删除的图片
      formModel.value.scenicAreaImages =
        formModel.value.scenicAreaImages.filter((image, i) => i !== index)

      // 从 fileList 中移除已删除的图片
      // fileList.value = fileList.value.filter((item, i) => i !== index)
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    console.error('删除图片失败:', error)
    ElMessage.error('删除图片失败，请稍后再试')
  }
}

// 坐标
const getLocation = (lng, lat) => {
  formModel.value.scenicAreaLongitude = lng
  formModel.value.scenicAreaLatitude = lat
}

// 语音
const handlePreview = (file) => {
  console.log('Preview file:', file)
}
// const handleRemove = (file) => {
//   console.log('Remove file:', file)
//   formModel.value.scenicAreaVoice = file.raw
//   videoList.value = file.raw
// }
const onVideo = (file) => {
  if (file) {
    videoUrl.value = URL.createObjectURL(file.raw)
    formModel.value.scenicAreaVoice = file.raw
    videoList.value.push({
      url: URL.createObjectURL(file.raw),
      name: file.raw.name,
      raw: file.raw
    })
  }
  // formModel.value.scenicAreaVoice.push(file.raw)
  console.log('File selected:', file.raw) // 打印文件信息
}

const emit = defineEmits(['success'])
const onPublish = async () => {
  if (!formModel.value.scenicAreaName) {
    ElMessage.error('景区名称不能为空')
    return
  }

  if (
    !formModel.value.scenicAreaVoice ||
    !(formModel.value.scenicAreaVoice instanceof File)
  ) {
    ElMessage.error('请选择有效的语音文件')
    return
  }
  const fd = new FormData()
  const textContent = formModel.value.scenicAreaInfo.replace(/<[^>]+>/g, '')
  if (Array.isArray(formModel.value.scenicAreaImages)) {
    formModel.value.scenicAreaImages.forEach((image, index) => {
      fd.append(`scenicAreaImages[${index}]`, image)
    })
  }

  fd.append('scenicAreaInfo', textContent)
  fd.append(
    'scenicAreaLongitude',
    parseFloat(formModel.value.scenicAreaLongitude) || 0
  )
  fd.append(
    'scenicAreaLatitude',
    parseFloat(formModel.value.scenicAreaLatitude) || 0
  )
  fd.append('scenicAreaName', formModel.value.scenicAreaName)

  fd.append('scenicAreaVoice', formModel.value.scenicAreaVoice)
  fd.append('scenicAreaVideo', videoList.value)
  // 图片的删除
  const fd2 = new FormData()

  // 确保id是有效的，如果不是编辑操作，则不应发送id字段
  const isEdit = formModel.value.id !== undefined && formModel.value.id !== null
  if (isEdit) {
    fd.append('id', parseInt(formModel.value.id))
    fd2.append('id', parseInt(formModel.value.id))
    if (Array.isArray(formModel.value.scenicAreaImages)) {
      formModel.value.scenicAreaImages.forEach((scenicAreaImage) => {
        fd2.append('scenicAreaImage', scenicAreaImage)
      })
    }

    console.log('Form data being sent:', Array.from(fd.entries())) // 打印FormData内容
    console.log('Form data being sent:', Array.from(fd2.entries())) // 打印FormData内容
    try {
      let res
      let res1
      if (isEdit) {
        console.log('isEdit', isEdit)
        res = await ScenicAreaUpdateService(fd)

        // 添加图片
        res1 = await ScenicAreaAddImgService(fd2)
        console.log('res', res)
        console.log('res1', res1)
      } else {
        res = await ScenicAreaAddService(fd)
      }
      console.log('Operation response:', res)
      if (res && res.code === 401) {
        ElMessage.error(res.message || '操作失败')
      } else {
        ElMessage.success(isEdit ? '编辑成功' : '添加成功')
        visibleDrawer.value = false
        emit('success')
      }
    } catch (error) {
      console.error('Form submission error:', error)
      ElMessage.error('表单提交失败，请检查输入')
    }
  }
}

const open = async (row) => {
  visibleDrawer.value = true
  console.log('row', row)
  console.log('formModel.value1', formModel.value)
  if (row.id) {
    videoUrl.value = row.scenicAreaVoice

    formModel.value.scenicAreaVoice = row.scenicAreaVoice
    // videoList.value = row.scenicAreaVideo
    const imagesWithUid = row.scenicAreaImages.map((imgUrl, index) => ({
      url: imgUrl,
      uid: -index - 1, // 使用负数确保唯一性
      name: `image-${index}.jpg` // 可以根据实际情况调整名称
    }))
    fileList.value = imagesWithUid
    // console.log('123435', row.scenicAreaImages)
    formModel.value = { ...defaultModel, ...row }
    // imgUrl.value = row.scenicAreaImage
  } else {
    formModel.value = { ...defaultModel }
    formModel.value.scenicAreaImages = []
    videoList.value = []
    formModel.value.scenicAreaInfo = ''
    formModel.value.scenicAreaLongitude = ''
    formModel.value.scenicAreaLatitude = ''
    imgUrl.value = ''
    editorRef.value.setHTML('')
    videoUrl.value = ''
    videoList.value = ''
  }
  console.log('formModel.value2', formModel.value)
}

defineExpose({ open })
</script>
<template>
  <el-drawer
    v-model="visibleDrawer"
    :title="formModel.id ? '编辑景区' : '添加景区'"
    direction="rtl"
    size="50%"
  >
    <!-- 发表表单 -->
    <el-form :model="formModel" ref="formRef" label-width="100px">
      <el-form-item label="景区名称" prop="scenicAreaName">
        <el-input
          v-model="formModel.scenicAreaName"
          placeholder="请输入景区名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="景区图片" prop="scenicAreaImage">
        <el-upload
          style="margin-left: 20px"
          class="avatar-uploader"
          :show-file-list="true"
          list-type="picture-card"
          v-model:file-list="fileList"
          :auto-upload="false"
          :on-change="onSelectFile"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          action="https://jsonplaceholder.typicode.com/posts/"
          ref="upload"
          ><i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog v-model:visible="dialogVisible"> </el-dialog>
      </el-form-item>
      <el-form-item label="景区语音" prop="scenicAreaVoice">
        <el-upload
          class="upload-demo"
          accept=".mp3"
          ref="upload"
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-preview="handlePreview"
          :before-upload="beforeUpload"
          v-model:file-list="videoList"
          :auto-upload="false"
          :on-change="onVideo"
        >
          <el-button type="primary">上传语音</el-button>

          <template #tip>
            <div class="el-upload__tip">只能上传mp3文件</div>
          </template>
        </el-upload>
        <audio :src="videoUrl" v-if="videoUrl">
          您的浏览器不支持 audio 元素。
        </audio>
      </el-form-item>
      <el-form :model="formModel" ref="formRef" label-width="100px">
        <el-form-item label="景点位置" inline>
          <div style="display: flex; align-items: center">
            <el-input
              class="mapInput"
              ref="maprefLo"
              placeholder="请输入景点区经度"
              v-model="formModel.scenicAreaLongitude"
              style="width: 200px; margin-right: 10px"
            ></el-input>
            <el-input
              ref="maprefLa"
              v-model="formModel.scenicAreaLatitude"
              placeholder="请输入景区维度"
              style="width: 200px; margin-right: 10px"
            ></el-input>
          </div>
          <!-- 接收数据 -->
          <map-container
            style="width: 100%"
            @getLglat="getLocation"
          ></map-container>
        </el-form-item>
      </el-form>
      <el-form-item label="景区介绍">
        <div class="editor">
          <quill-editor
            theme="snow"
            v-model:content="formModel.scenicAreaInfo"
            contentType="html"
            ref="editorRef"
          >
          </quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="onPublish" type="primary">发布</el-button>
        <el-button @click="visibleDrawer = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
.el-icon--upload {
  margin-left: 50px;
}
.mapInput {
  display: inline-block;
}
</style>
